<template>
  <div class="container" id="count">
    <el-row :gutter="20">
      <!-- right -->
      <el-col :span="24" :xs="24">
        <div class="devList-top">
          <span>选择设备：</span>
          <el-form :model="form">
            <el-form-item prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="mapTreeData"
                :show-count="true"
                @input="treeValueChange"
                placeholder="请输入设备号查询"
				:disableFuzzyMatching='true'
				style="width: 400px;"
              />
            </el-form-item>
          </el-form>
        </div>
        <el-card>
          <ul class="head">
            <!-- 今日步数 -->
            <li class="item today">
              <div class="line">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-tubiaozhexiantu1"></use>
                </svg>
              </div>
              <div class="context">
                <p>
                  {{
                    nowDate == lastDate
                      ? options.series[0].data[
                          options.series[0].data.length - 1
                        ]
                      : 0
                  }}
                </p>
                <span>{{ $t('count.step.today') }}</span>
              </div>
            </li>
            <!-- 总步数 -->
            <li class="item sum">
              <div class="line">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-tubiaozhexiantu1"></use>
                </svg>
              </div>
              <div class="context">
                <p>{{ arrStep }}</p>
                <span>{{ $t('count.step.sum') }}</span>
              </div>
            </li>
            <!-- 平均步数 -->
            <li class="item avg">
              <div class="line">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-tubiaozhexiantu1"></use>
                </svg>
              </div>
              <div class="context">
                <p>{{ arrStep ? Math.round(arrStep / 7) : 0 }}</p>
                <span>{{ $t('count.step.svg') }}</span>
              </div>
            </li>
          </ul>
          <!-- 步数图 -->
          <div style="height:64vh;width:100%;" ref="stepRef"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
// const echarts = require('echarts') // 导入echarts
// 引入 echarts 核心模块，核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core'
// 引入柱状图图表，图表后缀都为 Chart
import { BarChart, LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent,
  DataZoomComponent,
  DatasetComponent,
  TransformComponent
} from 'echarts/components'
// 标签自动布局，全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features'
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers'
import { cardStepNum } from '@/api/system/count' // import treeselect api
import { getDev } from '@/api/system/map'
import Treeselect from '@riophae/vue-treeselect' // import Treeselect component
import '@riophae/vue-treeselect/dist/vue-treeselect.css' // import Treeselect styles
const elementResizeDetectorMaker = require('element-resize-detector')
// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent,
  DataZoomComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  LineChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
])
export default {
  name: 'Step',
  components: {
    Treeselect
  },
  data () {
    return {
      isWatch: false,
      lineChart: undefined,
      nowDate: 0,
      lastDate: 0,
      arrStep: 0,
      form: {
        deptId: undefined
      },
      mapTreeData: [],
      quer2: {
        deptId: undefined
      },
      expandedKeys: [], //默认打开的节点
      deptOptions: undefined, // 部门树选项
      deptName: undefined, // 部门名称
      deptId: undefined,
      defaultProps: {
        children: 'children', // 指定子树为节点对象的某个属性值
        label: 'label' // 指定节点标签为节点对象的某个属性值
      },
      // echarts配置项
      options: {
        // animationDuration: 5000, // 图例翻页时的动画时长
        hoverLayerThreshold: 3000,
        // 标题
        title: {
          text: this.$t('count.step.lately')
        },
        // 提示
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        // 图例
        legend: {
          top: '5%'
          // data: []
        },
        // 网络
        grid: [
          {
            left: '2%',
            right: '4%',
            bottom: '14%',
            top: '16%',
            containLabel: true
          }
        ],
        // 工具
        toolbox: {
          show: true, // 是否显示工具栏组件
          showTitle: true, // 是否在鼠标 hover 的时候显示每个工具 icon 的标题
          // 各工具配置项
          feature: {
            // 数据视图
            dataView: {
              show: false,
              title: '数据视图',
              iconStyle: {
                borderColor: '#1e90ff'
              },
              emphasis: {
                iconStyle: {
                  borderColor: '#1e90ff'
                }
              }
            },
            // dataZoom: {}, // 数据区域缩放。目前只支持直角坐标系的缩放。
            // 切换视图类型
            magicType: {
              show: true,
              type: ['bar', 'line'],
              title: { bar: '切换为柱状图', line: '切换为折线图' },
              iconStyle: {
                borderColor: '#22bb22'
              },
              emphasis: {
                iconStyle: {
                  borderColor: '#22bb22'
                }
              }
            },
            // 刷新数据
            restore: {
              show: true, // 显示工具
              title: '刷新', // 标题
              iconStyle: {
                borderColor: '#d2691e'
              },
              emphasis: {
                iconStyle: {
                  borderColor: '#d2691e'
                }
              }
            },
            // 保存图片
            saveAsImage: {
              show: true,
              title: '保存图片',
              iconStyle: {
                borderColor: '#4b0082'
              },
              emphasis: {
                iconStyle: {
                  borderColor: '#4b0082'
                }
              }
            }
          }
        },
        // x轴
        xAxis: {
          type: 'category',
          offset: 15,
          boundaryGap: true,
          axisTick: {
            length: 7,
            alignWithLabel: false // 可以保证刻度线和标签对齐
          },
          // axisLabel : {//坐标轴刻度标签的相关设置。
          //   interval:0,
          //   rotate:"45"
          // },
          axisLine: {
            onZero: false,
            lineStyle: {
              color: '#0094ff'
            }
          },
          data: []
        },
        // y轴
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false,
            length: 15
          }
        },

        dataZoom: [
          {
            show: true,
            height: 14,
            xAxisIndex: [0],
            type: 'inside',
            bottom: '8%',
            start: 0,
            end: 100,
            handleIcon:
              'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
            handleSize: '110%',
            handleStyle: {
              color: '#d3dee5'
            },
            textStyle: {
              color: '#000'
            },
            borderColor: '#90979c'
          },
          {
            type: 'inside',
            show: true,
            height: 15,
            start: 1,
            end: 35
          }
        ],
        series: [
          {
            name: this.$t('count.step.steps'),
            type: 'bar',
            barWidth: 30,
            barGap: '13%',
            data: [],
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: '#fccb05'
                },
                {
                  offset: 1,
                  color: '#f5804d'
                }
              ]),
              borderRadius: 12
            },
            label: {
              show: true, //开启显示
              verticalAlign: 'middle',
              position: 'top',
              distance: 15,
              color: '#f79737',
              fontSize: 14,
              fontWeight: 700
            }
          }
        ]
      }
    }
  },
  created () {},
  methods: {
    // currDeptChange(val){
    //  if (val == null || val == undefined || val == '') {
    //  	return
    //  }
    //  if(val.length>8){
    // this.getCardstepNum(val)
    //  }else{
    // this.$message({
    //   showClose: true,
    //    message:'只能查询设备',
    //    type: 'warning'
    // });
    //  }
    // },
    treeValueChange (val) {
      if (val == null || val == undefined || val == '') {
        return
      }
      if (val.length > 8) {
        this.getCardstepNum()
      } else {
        this.$message({
          showClose: true,
          message: '只能查询设备',
          type: 'warning'
        })
        let that = this
        setTimeout(function () {
          that.form.deptId = undefined
        }, 100)
      }
    },
    // 获取设备步数
    getCardstepNum (card) {
      this.clearEcharts()
      this.arrStep = 0
      this.lastDate = 0
      cardStepNum(card).then(res => {
        if (res.code == 200) {
          if (res.data.length == 0) {
            this.$message({
              showClose: true,
              message: '当前设备暂无数据',
              type: 'warning'
            })
          }
          res.data.forEach((item, index) => {
            this.options.xAxis.data[index] = item.fAddTime.substring(0, 10)
            this.options.series[0].data[index] = item.fSteps
            this.arrStep += item.fSteps
          })
          this.getStepData()
          if (res.data.length > 0) {
            let reg = new RegExp('-', 'g')
            this.lastDate = parseInt(
              this.options.xAxis.data[
                this.options.xAxis.data.length - 1
              ].replace(reg, '')
            )
          }
        }
      })
    },

    getStepData () {
      // 初始化line
      if (
        this.lineChart != null &&
        this.lineChart != '' &&
        this.lineChart != undefined
      ) {
        this.lineChart.dispose()
      }
      // 基于准备好的dom，初始化echarts实例
      this.lineChart = echarts.init(this.$refs.stepRef)
      // 实例化line
      this.lineChart.setOption(this.options)
      // // 初始化line
      // var stepChart = echarts.init(this.$refs.stepRef)
      // // 实例化line
      // stepChart.setOption(this.options)
    },
    clearEcharts () {
      this.options.series[0].data = []
      this.options.xAxis.data = []
    },
    // 查询部门下拉树结构
    getTreeselect () {
      getDev(this.quer2)
        .then(response => {
          // console.log(response.data)
          this.mapTreeData = response.data
        })
        .catch(err => {
          console.log(err)
        })
    }
    // 筛选节点
    // filterNode (value, data) {
    //   if (!value) return true
    //   return data.label.indexOf(value) !== -1
    // },
    // 节点单击事件获得树结构Id
    //  handleNodeClick (data) {
    //    let card
    // if(data.id.length>8){
    //  card=data.id
    //  this.getCardstepNum(card)
    // }

    //  }
  },
  mounted () {
    let that = this
    var erd = elementResizeDetectorMaker()
    erd.listenTo(document.getElementById('count'), function (element) {
      var width = element.offsetWidth
      var height = element.offsetHeight
      if (that.lineChart) {
        that.$nextTick(function () {
          //使echarts尺寸重置
          that.lineChart.resize()
        })
      }
    })
    // this.getStepData()
    var date = new Date()
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    if (month < 10) {
      month = '0' + month
    }
    if (day < 10) {
      day = '0' + day
    }
    this.nowDate = parseInt(year + month + day)
  },
  watch: {
    // 根据名称筛选部门树
    deptName (val) {
      this.$refs.tree.filter(val)
    },
    deptOptions: {
      handler () {
        this.deptOptions.forEach(item => {
          this.expandedKeys.push(item.id)
        })
      },
      deep: true
    },
    // 监听deptId
    // 'form.deptId': 'currDeptChange',
    '$store.state.deptId': {
      handler (newval) {
        if (this.isWatch) {
          this.quer2.deptId = newval
          this.getTreeselect()
        }
      }
    }
  },
  activated () {
    this.isWatch = true
    if (this.$store.state.deptId) {
      this.quer2.deptId = this.$store.state.deptId // 把点击获得的id赋值给queryParams模型id
      this.getTreeselect()
    }
  },
  deactivated () {
    this.isWatch = false
  }
}
</script>
<style lang="scss" scoped>
::v-deep.container {
  .devList-top {
    height: 45px;
    background-color: #000;
    width: 100%;
    border-radius: 5px;
    line-height: 45px;
    span {
      color: #fff;
      margin-left: 10px;
      font-weight: 700;
      font-size: 15px;
    }
    .el-form {
      width: 300px;
      top: 3px;
      left: 110px;
      z-index: 999;
      position: absolute;
    }
	.vue-treeselect__menu{
		overflow-x: auto;
		width:310px;
	}
	
	.vue-treeselect div, .vue-treeselect span{
	box-sizing:content-box;
	}
  }
}
.head {
  display: flex;
  padding: 0;
  .item {
    width: 33%;
    height: 90px;
    margin-right: 20px;
    display: flex;
    .line {
      width: 35%;
      color: #ccc;
      font-size: 70px;
      line-height: 90px;
      padding-left: 15px;
      opacity: 0.4;
    }
    .context {
      color: #fff;
      width: 60%;
      text-align: right;
      p {
        font-size: 25px;
        margin: 10px 0;
      }
    }
  }
  .today {
    background-color: #dd667d;
  }
  .sum {
    background-color: #71b5e5;
  }
  .avg {
    background-color: #bb88c6;
  }
}
</style>
